Object Oriented Programming - Polymorphism

Polymorphism is the ability of an object to take on many forms. Say, If we have a button, there are many different draw outputs (round button, check button, square button, button with image) but they do share the same logic: onClick().

Polymorphism is based on the greek words Poly (many) and morphism (forms). We will create a structure that can take or use many forms of objects.

Polymorphism with a Function

We create three classes: ICICI, HDFC and SBI, every one of which has a unique interest rate. We then intialize all the instances and get their interest using the same method.


In [ ]:
class Bank(object):
    def interestRate():
        pass
    
class ICICI(Bank):
    def interestRate(self):
        return 8.12
    
class HDFC(Bank):
    def interestRate(self):
        return 5.3

class SBI(Bank):
    def interestRate(self):
        return 0.5

In [ ]:
#def getInterestRate(bankType):
#    return bankType.interestRate()

In [ ]:
accounts = [SBI(), ICICI(), HDFC()]

for account in accounts:
    print(account.interestRate())

Polymorphism with Abstract Classes

An example would be to have an abstract class Bank which holds the function interestRate().

We define three objects ICICI, HDFC and SBU, both are a form of Car. In pseudo code what we will do is:


In [ ]:
class Bank:
    def __init__(self, name):
        self.name = name
        
    def interestRate(self):
        raise NotImplementedError('Subclass must implement abstract method')

        
class ICICI(Bank):
    def interestRate(self):
        return 8.12
    
class HDFC(Bank):
    def interestRate(self):
        return 5.3

class SBI(Bank):
    def interestRate(self):
        return 0.5
    
accounts = [SBI('Arif'), ICICI('Sebastin'), HDFC('Mayank')]

for account in accounts:
    print(account.name + " is getting an interest rate of : " + str(account.interestRate()))

In [ ]:
class A():
    def save(self):
        print("Save in A")
class B():
    def save(self):
        print("Save in B")

class C(A,B):
    def __init__(self):
        pass
    
a = A()
c = C()
b = B()

super(A, c).save()